import {
  Button,
  Card,
  Col,
  Form,
  Input,
  Modal,
  Pagination,
  Row,
  Space,
  Switch,
  Table,
  message
} from 'antd'
import type { FormProps, TableColumnsType } from 'antd'
import { useBrand, usePutBrandId } from '@/api/query'
import { useEffect, useState } from 'react'

import { FormattedMessage } from 'react-intl'
import PubSub from 'pubsub-js'
import { SearchOutlined } from '@ant-design/icons'
import { useAppSelector } from '@/store/hooks'

export default function index() {
  // 品牌数据的类型限制
  interface DataType {
    _id: string
    key: number
    id: number
    name: string
    firstLetter: string
    sort: number
    showStatus: number
    productCount: number
    productCommentCount: number
    logo?: string
    offLineSales: number
  }

  // form 表单
  type FieldType = {
    username?: string
    password?: string
    remember?: string
  }

  // 品牌数据的字段设置
  const columns: TableColumnsType<DataType> = [
    {
      title: <FormattedMessage id="commodity_brand.id" />,
      dataIndex: 'id'
    },
    {
      title: <FormattedMessage id="commodity_brand.name"></FormattedMessage>,
      dataIndex: 'name',
      render: (text: string) => <a>{text}</a>
    },
    {
      title: (
        <FormattedMessage id="commodity_brand.firstLetter"></FormattedMessage>
      ),
      dataIndex: 'firstLetter'
    },
    {
      title: <FormattedMessage id="commodity_brand.sort"></FormattedMessage>,
      dataIndex: 'sort'
    },
    {
      title: (
        <FormattedMessage id="commodity_brand.showStatus"></FormattedMessage>
      ),
      render: (_, record) => (
        <Space>
          <Switch
            defaultChecked
            onChange={() => {
              onChange1(record)
            }}
          ></Switch>
        </Space>
      )
    },
    {
      title: (
        <FormattedMessage id="commodity_brand.productCount"></FormattedMessage>
      ),
      dataIndex: 'productCount'
    },
    {
      title: (
        <FormattedMessage id="commodity_brand.productCommentCount"></FormattedMessage>
      ),
      dataIndex: 'productCommentCount'
    },
    {
      title: <FormattedMessage id="commodity_brand.operate"></FormattedMessage>,
      dataIndex: 'operation',
      render: (_, record) => (
        <Space>
          <Button
            type="primary"
            onClick={() => {
              edit(record)
            }}
          >
            <FormattedMessage id="commodity_brand.edit"></FormattedMessage>
          </Button>
          <Button
            danger
            type="primary"
            onClick={() => {
              dele(record)
            }}
          >
            <FormattedMessage id="commodity_brand.delete"></FormattedMessage>
          </Button>
        </Space>
      )
    }
  ]

  // 编辑
  const edit = (record: DataType) => {
    showModal() // 打开模态框
    // 将当前行的数据设置到表单中
    form.setFieldsValue(record)
    setBrandDate(record)
  }
  // 删除
  const dele = (record: object) => {
    console.log(record)
  }

  // 获取redux数据
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const { definedLocale } = useAppSelector((state) => state.front)

  const onChange1 = (record: object) => {
    console.log('record====', record)
  }

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [pageNum, setPageNum] = useState(1) // 当前页
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [pageSize, setPageSize] = useState(5) // 每页个数
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [searchValue, setSearchValue] = useState<string>('') // 搜索内容的获取
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [searchBrand, setSearchBrand] = useState<string>('') // 搜索内容
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [isModalOpen, setIsModalOpen] = useState(false) // 模态框的打开

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [form] = Form.useForm() // 创建一个 Form 实例并获取 form 对象

  // eslint-disable-next-line react-hooks/rules-of-hooks,
  const [brandDate, setBrandDate] = useState<DataType>()

  // 用于获取最新获取要修改的对象
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [newObj, setNewObj] = useState<object>()

  const {
    isLoading,
    data,
    error
    // eslint-disable-next-line react-hooks/rules-of-hooks
  } = useBrand(pageNum, pageSize, searchBrand)

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const { mutate: mutateStatus } = usePutBrandId(newObj as DataType)
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [brandList, setBrandList] = useState<DataType[]>([])
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    if (data) {
      const dataSource = data.list?.map((item: DataType) => ({
        ...item,
        key: item.id
      }))
      setBrandList(dataSource)
    }
  }, [data])

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    if (!isLoading && !error && newObj) {
      mutateStatus()
    }
  }, [isLoading, error, newObj, mutateStatus])

  if (isLoading) {
    return <div>loading</div>
  }
  if (error) {
    return <div>error</div>
  }

  // 复选框的选中操作
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys)
  }
  // 删除复选框的设置
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange
  }
  // 分页操作
  const changPage = (page: number, pageSize: number) => {
    setPageNum(page) // 改变当前页
    setPageSize(pageSize) // 改变每页个数
  }

  // 触发查找方法
  const searchFunction = () => {
    setSearchBrand(searchValue)
  }

  //  模态框 modal 方法的操作
  const showModal = () => {
    setIsModalOpen(true)
  }
  //表单的提交
  const handleOk = async () => {
    try {
      await form.validateFields() // 校验表单字段
      form.submit() // 提交表单
    } catch (error) {
      message.error('校验失败!')
    }
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }
  // form表单 方法操作
  const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
    const obj = { ...brandDate, ...values }
    setNewObj(obj)
    await mutateStatus()
    message.success('修改成功')
    setIsModalOpen(false)
    PubSub.publish('change', '去后端拿数据')
  }

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (
    errorInfo
  ) => {
    console.log('Failed:', errorInfo)
  }

  return (
    <div>
      {/* 搜索层 */}
      <Card>
        {/* 一层介绍 */}
        <Row>
          <Col span={8}>
            <SearchOutlined />
            <FormattedMessage id="commodity_brand.search.filtering"></FormattedMessage>
          </Col>
          <Col span={8}></Col>
          <Col span={8} style={{ textAlign: 'right' }}>
            <Button type="primary" onClick={searchFunction}>
              <FormattedMessage id="commodity_brand.search.result"></FormattedMessage>
            </Button>
          </Col>
        </Row>
        {/* 二层搜索框展示 */}
        <Row>
          <Col span={3} style={{ textAlign: 'right' }}>
            <FormattedMessage id="commodity_brand.input.search"></FormattedMessage>
          </Col>
          <Col span={4}>
            <FormattedMessage id="commodity_brand.input.brand.name">
              {(placeholderText) => (
                <Input
                  placeholder={placeholderText}
                  onChange={(ele) => {
                    setSearchValue(ele.target.value)
                  }}
                  value={searchValue}
                />
              )}
            </FormattedMessage>
          </Col>
          <Col span={8}></Col>
          <Col span={8} style={{ textAlign: 'right' }}></Col>
        </Row>
      </Card>

      {/* 模态框展示 */}
      <Modal
        title="编辑数据"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          form={form} // 表单实例
          name="editForm" // 表单名称
        >
          <Form.Item
            label="品牌名称"
            name="name"
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="品牌首字母"
            name="firstLetter"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="排序"
            name="sort"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      {/* 展示层 */}
      <Card>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={brandList}
          pagination={{
            hideOnSinglePage: true
          }}
        />
        <Pagination
          total={data.total}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => {
            if (definedLocale == 'zh') {
              return `总共 ${total} 条`
            } else {
              return `Total ${total} items`
            }
          }}
          onChange={changPage}
          pageSizeOptions={['5', '10', '15', '20']}
          defaultPageSize={pageSize}
          current={pageNum}
        />
      </Card>
    </div>
  )
}
